package springboot.springboot06_ssmp.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import springboot.common_utils.JWTUtils;
import springboot.springboot06_ssmp.entity.Menu;
import springboot.springboot06_ssmp.entity.User;
import springboot.springboot06_ssmp.entity.UserRole;
import springboot.springboot06_ssmp.mapper.UserMapper;
import springboot.springboot06_ssmp.mapper.UserRoleMapper;
import springboot.springboot06_ssmp.service.IMenuService;
import springboot.springboot06_ssmp.service.IUserService;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author daiqiang
 * @since 2024-06-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private IMenuService menuService;
    @Override
    public IPage<User> getPage(int currentPage, int pageSize, User user) {

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(user.getUserName()),User::getUserName,user.getUserName());
        lqw.like(Strings.isNotEmpty(user.getPhone()),User::getPhone,user.getPhone());


        IPage page = new Page(currentPage,pageSize);
        userMapper.selectPage(page,lqw);
        return  page;

    }
    @Override
    public void update(User User) {

    }
    @Override    //注册，新增用户
    public void  addUser(User user) {
        // md5摘要加密
        user.setPassWord(SecureUtil.md5(user.getPassWord()));
        baseMapper.insert(user);

        List<Integer> roleIdList = user.getRoleIdList();
        if (roleIdList != null) {
            for (Integer roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }
    //20231213
    public Map<String, Object> login2(User user) {
        //根据用户名密码查询
        //LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        //lqw.eq(User::getUserName,user.getUserName());
        // lqw.eq(User::getPassWord,user.getPassWord());
        User loginUser=  userMapper.getUsernameAndPassword(user.getUserName(),user.getPassWord());
        //暂时用UUID，终极方案是JWT
       /* if(loginUser!=null){
            //String  key ="user:" + UUID.randomUUID();
            //存入redis
            try (Jedis jedis = JedisUtils.getJedis()) {   //java redis   连接池工具类  resources 目录下面
            //Jedis jedis = new Jedis("192.168.40.136", 6380);
                 //2.操redis
                loginUser.setPassWord(null);
                 jedis.set(key, JSON.toJSONString(loginUser));
                //返回数据
                Map<String, Object>  data=new HashMap<>();
                data.put("token",key);
                return data;
            } catch (Exception e) {
                System.out.println("Error connecting to Redis: " + e.getMessage());
            }

        }*/
        //JWT 方案
        if(loginUser!=null){

            loginUser.setPassWord(null);
            //创建JWT
            String token= JWTUtils.createToken(loginUser);
            //返回数据
            Map<String, Object>  data=new HashMap<>();
            data.put("token",token);
            return data;
        }
        return null;
    }//20231213
    //登录实现，token+获取用户信息，根据token获取用户信息
    @Override
    public Map<String, Object> getUserInfo(String token) {
        //根据token 获取用户信息
        //Jedis jedis = new Jedis(new HostAndPort("192.168.40.136",6380));
        //java redis   连接池工具类
        /*Jedis jedis = JedisUtils.getJedis();
        Object  obj =jedis.get(token);
        System.out.println(obj);
        if(obj!=null){
            User  loginUser= JSON.parseObject((String) obj,User.class);//反序列化成User对象
            Map<String, Object>  data=new HashMap<>();
            data.put("name",loginUser.getUserName());
            data.put("password",loginUser.getPassWord());
            //角色
            List<String> roleList=this.baseMapper.getUserNameByUserID(loginUser.getId());
            data.put("roles",roleList);

            return data;
        }*/
        User  loginUser=null;
        try {
            loginUser= JWTUtils.parseToken(token,User.class);
        }catch (Exception e){
            e.fillInStackTrace();
        }
        if(loginUser!=null){
            LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
            lqw.eq(User::getUserName,loginUser.getUserName());
            loginUser=this.baseMapper.selectOne(lqw);
            Map<String, Object>  data=new HashMap<>();
            data.put("name",loginUser.getUserName());
            data.put("avatar",loginUser.getAvatar());
            //角色
            List<String> roleList=this.baseMapper.getUsernameByUserID(loginUser.getId());
            data.put("roles",roleList);
            //权限列表
            List<Menu> menuList=menuService.getMenuListByUserID(loginUser.getId());
            data.put("menuList",menuList);

            return data;
        }
        return null;
    }
    //退出登录
    @Override
    public void logout(String token) {
        // Jedis jedis = JedisUtils.getJedis();   //jedis连接池
        //Jedis jedis = new Jedis(new HostAndPort("192.168.40.136",6380));
        //jedis.del(token);   //JWT方案，不用redis
    }

    @Override
    public User getUserById(Integer id) {
        User user=this.baseMapper.selectById(id);
        LambdaQueryWrapper<UserRole>  wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoleList=userRoleMapper.selectList(wrapper);
        List<Integer> roleIdList=userRoleList.stream().map(UserRole::getRoleId)
                .collect(Collectors.toList());
        user.setRoleIdList(roleIdList);
        return user;
    }

    @Override
    @Transactional
    public void updateUserById(User user) {
        //1.更新用户表
        this.baseMapper.updateById(user);
        //2.清除原有角色
        LambdaQueryWrapper<UserRole>  wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(wrapper);
        //3.设置新的角色
        List<Integer> roleIdList=user.getRoleIdList();
         if(roleIdList!=null){
            for (Integer roleId:roleIdList){
                userRoleMapper.insert(new UserRole(null, user.getId(), roleId));
            }
        }

    }
    @Transactional
    @Override
    public void deleteUserById(Integer id) {
        //1.删除角色表
        //2.删除角色菜单表
        this.baseMapper.deleteById(id);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(wrapper);
    }
}
